﻿using PluginDependencyTest;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


            var dllName = "dddxxfd.dll";
            var s = dllName.Substring(0, dllName.Length - 4);
            Console.WriteLine(s);

            Test();
        }

        public static List<AssemblyName> ParseAssemblyNames(string input)
        {
            List<AssemblyName> assemblyNames = new List<AssemblyName>();

            // 正则表达式匹配程序集信息，包括简单的dll名称
            //string pattern = @"(?:\/\/\s*(?<name>[^,]+),\s*Version=(?<version>[^,]+),\s*Culture=(?<culture>[^,]+),\s*PublicKeyToken=(?<token>[^\r\n\s]+))|(?:^\s*(?<simplename>[^\s]+\.dll)\s*$)";

            string pattern = @"^\s*\/\/\s*(?<name>[^,]+),\s*Version=(?<version>[^,]+),\s*Culture=(?<culture>[^,]+),\s*PublicKeyToken=(?<token>[^\r\n]+)(?!.*Success)";

            MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.Multiline);

            foreach (Match match in matches)
            {
                if (match.Groups["name"].Success)
                {
                    var name = match.Groups["name"].Value.Trim();
                    if (name.Contains(" "))
                        continue;

                    assemblyNames.Add(new AssemblyName
                    {
                        Name = name,
                        Version = new Version(match.Groups["version"].Value.Trim()),
                        //CultureInfo = new CultureInfo(match.Groups["culture"].Value.Trim()),
                        //PublicKeyToken = match.Groups["token"].Value.Trim()
                    });
                }
                else if (match.Groups["simplename"].Success)
                {
                    assemblyNames.Add(new AssemblyName
                    {
                        Name = match.Groups["simplename"].Value.Trim(),
                        //Version = null,
                        //CultureName = null,
                        //PublicKeyToken = null
                    });
                }
            }

            return assemblyNames;
        }

        static List<AssemblyName> ParseAssemblyNames2(string input)
        {
            List<AssemblyName> assemblyNames = new List<AssemblyName>();

            // 正则表达式匹配两种格式
            //string pattern = @"(?<name>[a-zA-Z0-9._]+), Version=(?<version>\d+\.\d+\.\d+\.\d+), Culture=(?<culture>[^,]+), PublicKeyToken=(?<token>[a-f0-9]+)|(?<name2>[a-zA-Z0-9._]+\.dll)";
            string pattern = @"(?<name>[a-zA-Z0-9._]+), Version=(?<version>\d+\.\d+\.\d+\.\d+), Culture=(?<culture>[^,]+), PublicKeyToken=(?<token>[a-f0-9]+)|(?<name2>[a-zA-Z0-9._-]+\.dll)";

            MatchCollection matches = Regex.Matches(input, pattern);

            foreach (Match match in matches)
            {
                if (match.Groups["name"].Success)
                {
                    // 提取第一种格式
                    string name = match.Groups["name"].Value;
                    string version = match.Groups["version"].Value;
                    string culture = match.Groups["culture"].Value;
                    string token = match.Groups["token"].Value;

                    var assembly = new AssemblyName($"{name}, Version={version}, Culture={culture}, PublicKeyToken={token}");

                    assemblyNames.Add(assembly);
                }
                else if (match.Groups["name2"].Success)
                {
                    // 提取第二种格式
                    string name = match.Groups["name2"].Value;
                    assemblyNames.Add(new AssemblyName(name));
                }
            }

            return assemblyNames;
        }

        static byte[] GetPublicKeyToken(string token)
        {
            if (string.IsNullOrEmpty(token))
                return null;

            byte[] publicKeyToken = new byte[token.Length / 2];
            for (int i = 0; i < token.Length; i += 2)
            {
                publicKeyToken[i / 2] = Convert.ToByte(token.Substring(i, 2), 16);
            }
            return publicKeyToken;
        }

        public void Test()
        {
            string input = @"// Detected TargetFramework-Id: .NETFramework,Version=v4.8
// Detected RuntimePack: Microsoft.WindowsDesktop.App

// Referenced assemblies (in metadata order):
// mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	// Assembly reference loading information:
	// Info: Success - Found in Assembly List

// mscorlib, Version=65535.65535.65535.65535, Culture=neutral, PublicKeyToken=b77a5c561934e089 (unresolved)
// PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 (unresolved)
// PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 (unresolved)
// System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	// Assembly reference loading information:
	// Info: Success - Found in Assembly List

// System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	// Assembly reference loading information:
	// Info: Success - Found in Assembly List

// System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	// Assembly reference loading information:
	// Info: Success - Found in Assembly List

// System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 (unresolved)
// WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 (unresolved)


// Assembly load log including transitive references:
// mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	// Info: Success - Found in Assembly List

// System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	// Info: Success - Found in Assembly List

// System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	// Info: Success - Found in Assembly List

// System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	// Info: Success - Found in Assembly List

   System.dll
System.Drawing.dll   ATRC.dll
    SZEW.dll
    SZEWGeologyDrawing.dll
    ATCMG.dll
    MSVCP140.dll
    api-ms-win-crt-convert-l1-1-0.dll
    api-ms-win-crt-time-l1-1-0.dll
    api-ms-win-crt-math-l1-1-0.dll
    mscoree.dll

";
            List<AssemblyName> assemblyNames = ParseAssemblyNames(input);

            List<AssemblyName> assemblyNames2 = ParseAssemblyNames2(input);

            foreach (AssemblyName assemblyName in assemblyNames)
            {
                Console.WriteLine(assemblyName);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            new MainForm().ShowDialog();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var analyzer = new HybridDependencyAnalyzer();
            var dllPath = @"D:\Program Files (x86)\ATEC\SSDP\SSDP\SZEWBoreholeGeologyTools.dll";
            //var dllPath = @"D:\Program Files (x86)\ATEC\SSDP\SSDP\AssistantNet.dll";
            var result = analyzer.AnalyzeHybridDependencies(dllPath);

            if (!string.IsNullOrEmpty(result.ErrorMessage))
            {
                Console.WriteLine($"错误: {result.ErrorMessage}");
                return;
            }

            Console.WriteLine("托管依赖:");
            result.ManagedDependencies.ForEach(Console.WriteLine);

            Console.WriteLine("\n原生依赖:");
            result.NativeDependencies.ForEach(Console.WriteLine);

            var analyzer2 = new DumpbinAnalyzer();
            var dependencies = analyzer2.GetNativeDependencies(dllPath);

            Console.WriteLine("原生依赖:");
            foreach (var dep in dependencies)
            {
                Console.WriteLine($"    {dep}");
            }
        }
    }
}
